from devdb import Model
import os
import base64
import yaml
import cherrypy

Computer = Model('Computer', 'hostname ip interfaces os key cookie')
Package = Model('Package', 'name description data')

config = yaml.load(open('config.yaml'))

def register(password):
    if password != config['register_password']:
        raise ValueError('bad password')
    cookie = base64.urlsafe_b64encode(os.urandom(21)).decode('ascii')
    comp = Computer(interfaces=[], cookie=cookie)
    comp.put()
    return comp.id + ':' + cookie

def ping(cookie, data):
    comp = get_by_cookie(cookie)
    comp.hostname = data['hostname']
    comp.interfaces = data['interfaces']
    comp.ip = cherrypy.request.remote.ip
    comp.key = data['key']
    comp.os = data['os']
    comp.put()

def get_by_cookie(cookie):
    ident, main_cookie = cookie.split(':')
    comp = Computer.get_by_id(ident)
    if comp.cookie != main_cookie:
        raise KeyError(main_cookie)
    else:
        return comp

def new_package(name, descr):
    pack = Package(name=name, description=descr, data={})
    pack.put()
    
    return pack.id

if __name__ == '__main__':
    c = Computer(ip='11.22.33.44')
    c.put()